﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

namespace JingQiao.Ads.Infrastructure.Data.EF.Repository
{
    using Domain.Model;
    using Domain.Model.DomainObject;
    using Domain.Model.Repository;

    public class AdvertisementRepository : BaseRepository<IAdvertisement>, IAdvertisementRepository
    {
        public AdvertisementRepository(IContext context)
            : base(context)
        {
            
        }

        public bool IsThrowed(int advertisementId)
        {
            return this._context.DestPositionAd.Any(x => x.AdvertisementId == advertisementId);
        }

        public IAdvertisement FindById(int id)
        {
            Check.Argument.IsNotNegativeOrZero(id, "id");

            return this._context.Advertisement.FirstOrDefault(ad => ad.AdvertisementId == id);
        }

        public PagedResult<IAdvertisement> FindAll(int pageSize, int pageIndex)
        {
            var ads = this._context.Advertisement.OrderByDescending(ad => ad.CreateDate)
                .Skip(pageSize * pageIndex)
                .Take(pageSize);
            var count = CountAll();

            return BuildPagedResult<IAdvertisement>(ads, count);
        }

        public PagedResult<IAdvertisement> FindByKeyWord(int pageSize, int pageIndex, string keyWord)
        {
            if (string.IsNullOrEmpty(keyWord))
            {
                return this.FindAll(pageSize, pageIndex);
            }
            else
            {
                var ads = this._context.Advertisement.Where(c => c.Title.Contains(keyWord))
                    .OrderByDescending(ad => ad.CreateDate)
                    .Skip(pageSize * pageIndex)
                    .Take(pageSize);
                var count = CountByKeyWord(keyWord);

                return BuildPagedResult<IAdvertisement>(ads, count);
            }
        }

        public int CountByKeyWord(string keyWord)
        {
            return this._context.Advertisement.Where(c => c.Title.Contains(keyWord)).Count();
        }

        public int CountAll()
        {
            return this._context.Advertisement.Count();
        }
    }
}
